const jwt = require("jsonwebtoken");
const {
	REQUIRED,
	NOEXISTS,
	INCORRENT,
	UNAUTHORIZATION,
} = require("../config/error.js");
const userServer = require("../server/userServer.js");
const md5password = require("../utils/md5handle.js");
const { PRIVATE_KEY, PUBLIC_KEY } = require("../config/secret.js");

// 验证用户
const verifyLogin = async (ctx, next) => {
	const { name, password } = ctx.request.body;
	// 1. 验证密码和用户名是否为空
	if (!name || !password) {
		return ctx.app.emit("error", REQUIRED, ctx);
	}

	// 2. 查询该用户是否存在于数据库
	const users = await userServer.findUserByName(name);
	const res = users[0];
	if (!res) {
		return ctx.app.emit("error", NOEXISTS, ctx);
	}

	// 3. 查询数据库中密码和参数里的密码是否一致
	if (res.password !== md5password(password)) {
		return ctx.app.emit("error", INCORRENT, ctx);
	}

	// 4. 将获取的用户消息 暂时存到ctx里
	ctx["user"] = res;

	await next();
};

// 验证token是否有效
const verifyAuth = async (ctx, next) => {
	// 1. 获取token

	const token = ctx.headers.authorization;
	if(!token){
		return 	ctx.app.emit("error", UNAUTHORIZATION, ctx);
	}
	// 2. 验证token是否有效
	try {
		const res = jwt.verify(token, PRIVATE_KEY, { algorithms: ["RS256"] });
		// 将token 也保存在ctx的user对象
		ctx["user"] = res;
		console.log('ctx.user:' ,res);
		await next();
	} catch (error) {
		console.log(error);
		ctx.app.emit("error", UNAUTHORIZATION, ctx);
	}
};

module.exports = { verifyLogin, verifyAuth };
